/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.nhncorp.neptune.client.shell;

import java.io.IOException;
import java.util.Map;

import com.nhncorp.neptune.client.NTableManager;
import com.nhncorp.neptune.client.Shell;
import com.nhncorp.neptune.client.nql.statement.ExecStatus;
import com.nhncorp.neptune.common.LockServiceFactory;
import com.nhncorp.neptune.common.conf.NConfiguration;
import com.nhncorp.neptune.common.ipc.AclManager;
import com.nhncorp.pleiades.client.LockService;
import com.nhncorp.pleiades.protocol.LockMetaData;

public class ShowUserStatement extends ShellStatement {
  @Override
  public String getPrefix() {
    return StatementFactory.SHOW_USER;
  }

  @Override
  public ExecStatus execute(NConfiguration conf) {
    ExecStatus status = new ExecStatus();
    try {
      LockService lockService = NTableManager.getLockService(conf);
      
      boolean isAdmin = AclManager.isSuperGroup(lockService, conf.getUserId());
      
      Map<String, LockMetaData> metas = lockService.readDir(com.nhncorp.neptune.common.Constants.USERS);
      int count = 0;
      if(metas != null && metas.size() > 0) {
        for(LockMetaData eachMeta: metas.values()) {
          String userId = LockServiceFactory.getLockMetaDataPathName(eachMeta);
          
          if(isAdmin || !AclManager.isSuperGroup(lockService, userId)) {
            System.out.printf("%s\n", userId);
            count++;
          }
        }
      }      
      status.setMessage(count + " users found.");
    } catch (IOException e) {
      status.setException(e);
    }  
    return status;
  }

  @Override
  public HelpUsage getHelpUsage() {
    return new HelpUsage(getPrefix(), "list users.(only supergroup)", "SHOW USERS");
  }
}
